package com.example.patchouli_knowledge

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.screenshot_service.ScreenshotPlugin
import com.example.screenshot_service.SmartFloatingBallService
import com.example.screenshot_service.PersistentScreenCaptureService
import android.media.projection.MediaProjectionManager
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity : FlutterActivity() {
    companion object {
        private const val TAG = "MainActivity"
        private const val LONG_PRESS_CHANNEL = "com.example.patchouli_knowledge/long_press"
        private const val SMART_FLOATING_BALL_CHANNEL = "com.example.patchouli_knowledge/smart_floating_ball"
        private const val OVERLAY_PERMISSION_REQUEST_CODE = 1234
        private const val VIBRATE_PERMISSION_REQUEST_CODE = 1235
        private const val PERSISTENT_CAPTURE_REQUEST_CODE = 1236
        
        // 全局可访问的方法通道，用于从服务通知Flutter
        var longPressChannel: MethodChannel? = null
        var smartFloatingBallChannel: MethodChannel? = null
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 检查并请求权限
        checkAndRequestPermissions()
        
        // 处理来自智能悬浮球的Intent
        handleSmartFloatingBallIntent(intent)
    }
    
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        // 处理新的Intent（当应用已在后台运行时）
        handleSmartFloatingBallIntent(intent)
    }
    
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        
        // 注册截图插件
        flutterEngine.plugins.add(ScreenshotPlugin())
        
        // 设置长按检测方法通道
        longPressChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, LONG_PRESS_CHANNEL)
        longPressChannel?.setMethodCallHandler { call, result ->
            when (call.method) {
                "startDetection" -> {
                    if (checkOverlayPermission()) {
                        startLongPressDetectionService()
                        result.success(true)
                    } else {
                        requestOverlayPermission()
                        result.success(false)
                    }
                }
                "stopDetection" -> {
                    stopLongPressDetectionService()
                    result.success(true)
                }
                else -> {
                    result.notImplemented()
                }
            }
        }
        
        // 设置智能悬浮球方法通道
        smartFloatingBallChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, SMART_FLOATING_BALL_CHANNEL)
        smartFloatingBallChannel?.setMethodCallHandler { call, result ->
            when (call.method) {
                "startSmartFloatingBall" -> {
                    if (checkOverlayPermission()) {
                        startSmartFloatingBallService()
                        result.success(true)
                    } else {
                        requestOverlayPermission()
                        result.success(false)
                    }
                }
                "stopSmartFloatingBall" -> {
                    stopSmartFloatingBallService()
                    result.success(true)
                }
                "isSmartFloatingBallRunning" -> {
                    result.success(SmartFloatingBallService.isRunning())
                }
                "requestScreenshot" -> {
                    // 当智能悬浮球请求截图时，通知Flutter执行截图
                    smartFloatingBallChannel?.invokeMethod("onScreenshotRequested", null)
                    result.success(true)
                }
                "initPersistentCapture" -> {
                    // 初始化持久截屏服务
                    requestPersistentCapturePermission()
                    result.success(true)
                }
                "isPersistentCaptureRunning" -> {
                    result.success(PersistentScreenCaptureService.isRunning())
                }
                "stopPersistentCapture" -> {
                    stopPersistentCaptureService()
                    result.success(true)
                }
                else -> {
                    result.notImplemented()
                }
            }
        }
    }
    
    /**
     * 检查并请求必要的权限
     */
    private fun checkAndRequestPermissions() {
        // 检查震动权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.VIBRATE) 
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.VIBRATE),
                VIBRATE_PERMISSION_REQUEST_CODE
            )
        }
    }
    
    /**
     * 检查悬浮窗权限
     */
    private fun checkOverlayPermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Settings.canDrawOverlays(this)
        } else {
            true // Android 6.0以下默认有权限
        }
    }
    
    /**
     * 请求悬浮窗权限
     */
    private fun requestOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val intent = Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:$packageName")
            )
            startActivityForResult(intent, OVERLAY_PERMISSION_REQUEST_CODE)
        }
    }
    
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            OVERLAY_PERMISSION_REQUEST_CODE -> {
                if (checkOverlayPermission()) {
                    // 权限已授予，但不要自动启动服务
                    // 只有当用户明确要求时才启动服务
                    Log.d(TAG, "悬浮窗权限已授予")
                    longPressChannel?.invokeMethod("onPermissionGranted", null)
                } else {
                    Log.w(TAG, "悬浮窗权限被拒绝")
                    longPressChannel?.invokeMethod("onPermissionDenied", null)
                }
            }
            PERSISTENT_CAPTURE_REQUEST_CODE -> {
                if (resultCode == RESULT_OK && data != null) {
                    // MediaProjection权限已授权
                    PersistentScreenCaptureService.projectionResultCode = resultCode
                    PersistentScreenCaptureService.projectionResultData = data
                    PersistentScreenCaptureService.hasProjectionPermission = true
                    
                    // 启动持久截屏服务
                    startPersistentCaptureService()
                    
                    Log.d(TAG, "MediaProjection权限已授权，启动持久截屏服务")
                    smartFloatingBallChannel?.invokeMethod("onPersistentCaptureReady", null)
                } else {
                    Log.w(TAG, "MediaProjection权限被拒绝")
                    smartFloatingBallChannel?.invokeMethod("onPersistentCapturePermissionDenied", null)
                }
            }
            else -> {
                super.onActivityResult(requestCode, resultCode, data)
            }
        }
    }
    
    /**
     * 启动长按检测服务
     */
    private fun startLongPressDetectionService() {
        try {
            val intent = Intent(this, LongPressDetectionService::class.java)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
            Log.d(TAG, "长按检测服务启动命令已发送")
        } catch (e: Exception) {
            Log.e(TAG, "启动长按检测服务失败: ${e.message}")
        }
    }
    
    /**
     * 停止长按检测服务
     */
    private fun stopLongPressDetectionService() {
        try {
            val intent = Intent(this, LongPressDetectionService::class.java)
            stopService(intent)
            Log.d(TAG, "长按检测服务停止命令已发送")
        } catch (e: Exception) {
            Log.e(TAG, "停止长按检测服务失败: ${e.message}")
        }
    }
    
    /**
     * 启动智能悬浮球服务
     */
    private fun startSmartFloatingBallService() {
        try {
            val intent = Intent(this, SmartFloatingBallService::class.java)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
            Log.d(TAG, "智能悬浮球服务启动命令已发送")
        } catch (e: Exception) {
            Log.e(TAG, "启动智能悬浮球服务失败: ${e.message}")
        }
    }
    
    /**
     * 停止智能悬浮球服务
     */
    private fun stopSmartFloatingBallService() {
        try {
            val intent = Intent(this, SmartFloatingBallService::class.java)
            stopService(intent)
            Log.d(TAG, "智能悬浮球服务停止命令已发送")
        } catch (e: Exception) {
            Log.e(TAG, "停止智能悬浮球服务失败: ${e.message}")
        }
    }
    
    /**
     * 处理来自智能悬浮球的Intent
     */
    private fun handleSmartFloatingBallIntent(intent: Intent?) {
        when (intent?.action) {
            "SMART_SCREENSHOT_ACTION" -> {
                val command = intent.getStringExtra("command")
                val source = intent.getStringExtra("source")
                
                Log.d(TAG, "收到智能悬浮球命令: $command, 来源: $source")
                
                when (command) {
                    "screenshot" -> {
                        // 通知Flutter执行截图
                        smartFloatingBallChannel?.invokeMethod("onScreenshotRequested", mapOf(
                            "source" to source,
                            "timestamp" to System.currentTimeMillis()
                        ))
                    }
                }
            }
            "REQUEST_CAPTURE_PERMISSION" -> {
                // 悬浮球请求截屏权限
                val source = intent.getStringExtra("source")
                val startPersistentService = intent.getBooleanExtra("startPersistentService", false)
                
                Log.d(TAG, "收到截屏权限请求，来源: $source, 启动服务: $startPersistentService")
                
                if (startPersistentService) {
                    requestPersistentCapturePermission()
                }
            }
            "CAPTURE_RESULT" -> {
                // 截屏结果
                val imagePath = intent.getStringExtra("imagePath")
                val success = intent.getBooleanExtra("success", false)
                
                Log.d(TAG, "收到截屏结果: 成功=$success, 路径=$imagePath")
                
                if (success && imagePath != null) {
                    // 截屏成功，直接导航到上传页面
                    smartFloatingBallChannel?.invokeMethod("onScreenshotSuccess", mapOf(
                        "imagePath" to imagePath,
                        "navigateToUpload" to true,
                        "timestamp" to System.currentTimeMillis()
                    ))
                } else {
                    // 截屏失败
                    smartFloatingBallChannel?.invokeMethod("onScreenshotResult", mapOf(
                        "success" to false,
                        "imagePath" to imagePath,
                        "timestamp" to System.currentTimeMillis()
                    ))
                }
            }
            "PROJECTION_STOPPED" -> {
                // MediaProjection被停止，需要重新授权
                Log.w(TAG, "MediaProjection已停止，通知Flutter重新授权")
                
                smartFloatingBallChannel?.invokeMethod("onProjectionStopped", mapOf(
                    "reason" to "MediaProjection已停止",
                    "needReauthorization" to true,
                    "timestamp" to System.currentTimeMillis()
                ))
                
                // 自动尝试重新请求权限
                requestPersistentCapturePermission()
            }
        }
    }
    
    /**
     * 请求持久截屏权限 - Android 14兼容版本
     */
    private fun requestPersistentCapturePermission() {
        try {
            Log.d(TAG, "请求MediaProjection权限 - Android 14兼容模式")
            
            val mediaProjectionManager = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
            val captureIntent = mediaProjectionManager.createScreenCaptureIntent()
            startActivityForResult(captureIntent, PERSISTENT_CAPTURE_REQUEST_CODE)
            
        } catch (e: Exception) {
            Log.e(TAG, "请求MediaProjection权限失败: ${e.message}")
            smartFloatingBallChannel?.invokeMethod("onPersistentCapturePermissionError", mapOf(
                "error" to e.message,
                "timestamp" to System.currentTimeMillis()
            ))
        }
    }
    
    /**
     * 启动持久截屏服务
     */
    private fun startPersistentCaptureService() {
        try {
            val intent = Intent(this, PersistentScreenCaptureService::class.java).apply {
                action = "INIT_PROJECTION"
            }
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
            
            Log.d(TAG, "持久截屏服务启动命令已发送")
        } catch (e: Exception) {
            Log.e(TAG, "启动持久截屏服务失败: ${e.message}")
        }
    }
    
    /**
     * 停止持久截屏服务
     */
    private fun stopPersistentCaptureService() {
        try {
            val intent = Intent(this, PersistentScreenCaptureService::class.java)
            stopService(intent)
            
            Log.d(TAG, "持久截屏服务停止命令已发送")
        } catch (e: Exception) {
            Log.e(TAG, "停止持久截屏服务失败: ${e.message}")
        }
    }
}
